package com.leetcode;

/**
 * 416. 分割等和子集
 *
 * @author fy
 * @date 2022/3/29 22:12
 */
public class Solution416 {

    /**
     * 416. 分割等和子集
     *
     * @param nums
     * @return
     */
    public boolean canPartition(int[] nums) {
        if (nums == null || nums.length < 2) {
            return false;
        }
        int n = nums.length;
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += nums[i];
        }
        if (sum % 2 != 0) {
            return false;
        }
        int c = sum >> 1;
        boolean[] dp = new boolean[c + 1];
        for (int i = 0; i <= c; i++) {
            dp[i] = i == nums[0];
        }

        for (int i = 1; i < n; i++) {
            int num = nums[i];
            for (int j = c; j >= num; j--) {
                dp[j] = dp[j] || dp[j - num];
            }
        }
        return dp[c];
    }

    public boolean canPartition1(int[] nums) {
        int n = nums.length;
        if (n < 2) {
            return false;
        }
        int sum = 0, maxNum = 0;
        for (int num : nums) {
            sum += num;
            maxNum = Math.max(maxNum, num);
        }
        if (sum % 2 != 0) {
            return false;
        }
        int target = sum / 2;
        if (maxNum > target) {
            return false;
        }
        boolean[] dp = new boolean[target + 1];
        dp[0] = true;
        for (int i = 0; i < n; i++) {
            int num = nums[i];
            for (int j = target; j >= num; --j) {
                dp[j] |= dp[j - num];
            }
        }
        return dp[target];
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 5, 11, 5};
        new Solution416().canPartition(nums);
    }
}
